﻿using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.ViewModel;
using log4net;
using System;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    public class LoginController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        BLL.UserInfo userinfobll = new BLL.UserInfo(); 
        [HttpPost]
        public IHttpActionResult Login(VM_LoginInfo model)
        {
            log.Info($"UserId:{model.UserId};Password:{model.Password}") ;

            //验证用户名密码正确性
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                IPR_StudyMeetingMrgSys.Model.UserInfo muserinfo= userinfobll.GetModel(" UserID='"+model.UserId+"' and UserPwd='"+model.Password+"'");
                if (muserinfo != null)
                {
                    //插入缓存
                    string token = Guid.NewGuid().ToString();
                    int tokenExpireTime = int.Parse(ConfigurationManager.AppSettings["TokenExpireTime"] ?? "1800");
                    HttpRuntime.Cache.Insert(model.UserId, token, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(tokenExpireTime));
                    HttpRuntime.Cache.Insert(token, muserinfo, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(tokenExpireTime));

                    //返回token信息
                    resultMsg.Info = "登录成功";
                    resultMsg.Data = muserinfo.UserName+"|"+token;
                    resultMsg.Count = 1;
                    LoginUser.UserInfo = muserinfo;
                    LoginUser.DepID = muserinfo.DeptID;
                    DataSet ds = new BLL.Dep().GetDepList(LoginUser.UserInfo.DeptID.ToString());
                    if(ds!=null)
                        if(ds.Tables.Count>0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                LoginUser.DepLevel = Convert.ToInt32(ds.Tables[0].Rows[0]["DepLevel"].ToString()); 
                                LoginUser.DepPID = Convert.ToInt32(ds.Tables[0].Rows[0]["DepPID"].ToString());
                                LoginUser.DepPLevel = Convert.ToInt32(ds.Tables[0].Rows[0]["DepPLevel"].ToString());
                            }
                        }
                    LoginUser.ButtonPowerList = new System.Collections.Generic.List<string>();
                    DataTable dt = new BLL.ModuleButtonSet().GetList(" UserID='" + model.UserId + "'").Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            LoginUser.ButtonPowerList.Add(dt.Rows[i]["MBName"].ToString());
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    resultMsg.Info = "登录失败，用户名或密码不正确";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        [HttpPost]
        [Route("api/GetModule")]
        public IHttpActionResult GetModule()
        {
            ResultMsg resultMsg = new ResultMsg();
            //部门ID需要修改为使用roleid来判断 
            int? roleid = LoginUser.UserInfo.RoleID;
            BLL.RoleSet rp = new BLL.RoleSet();
            string strwhere = string.Empty;
            if (!LoginUser.IsSuperAdmin)
            {
                strwhere = " RoleID = " + roleid;
            }
            DataTable dt = rp.GetList(strwhere).Tables[0];
            if (dt.Rows.Count > 0)
            {
                BLL.Module mod = new BLL.Module();
                if (!LoginUser.IsSuperAdmin)
                {
                    string smodid = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        smodid += dt.Rows[i]["ModID"].ToString() + ",";
                    }
                    strwhere = "modid in ( " + smodid.Trim(',') + " )";
                }
                dt = mod.GetList(strwhere).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Count = dt.Rows.Count;
                    resultMsg.Data = dt;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                    resultMsg.Data = "";
                }
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText()+",请设置权限！";
                resultMsg.Data = "";
            }


            return Json(resultMsg);
        }

        [HttpPost]
        [Route("api/GetPowerList")]
        public IHttpActionResult GetPowerList()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.Data = LoginUser.ButtonPowerList;
            resultMsg.Count = 1;
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            return Json(resultMsg);
        }

    }
}
